package com.df.happylearn.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.df.happylearn.R;
import com.df.happylearn.application.Constants;
import com.df.happylearn.cache.CacheUtil;
import com.df.happylearn.model.Article;
import com.df.happylearn.request.DataRequest;
import com.df.happylearn.sqlite.Helper;
import com.df.happylearn.ui.adapter.ArticleAdapter;
import com.df.happylearn.ui.view.utils.LoadStateUtil;
import com.df.happylearn.ui.view.utils.StateEnum;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Subscriber;

public class MainActivity extends BaseActivity {

    @Bind(R.id.back)
    RelativeLayout back;
    @Bind(R.id.txtTitle)
    TextView txtTitle;
    @Bind(R.id.refreshlayout)
    SwipeRefreshLayout mRefreshLayout;
    @Bind(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @Bind(R.id.loadFail)
    View loadFail;

    private ArticleAdapter mAdapter;
    private List<Article> mArticleList = new ArrayList<>();
    private LinearLayoutManager mLayoutManager;

    private int page = 0;
    private int offset = 0;
    private final static int LIMIT = 15;
    private boolean isLoading = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        initView();
        initData();
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_main;
    }

    private void initView() {
        txtTitle.setText(R.string.app_name);
        back.setVisibility(View.GONE);
        mRefreshLayout.setColorSchemeResources(new int[]{R.color.bg_actionbar});
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mAdapter = new ArticleAdapter(this, mArticleList);
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.addOnScrollListener(onScrollListener);
        mAdapter.setOnItemClickListener(onItemClickListener);
        mRefreshLayout.setOnRefreshListener(onRefreshListener);
    }

    private void initData() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mRefreshLayout.setRefreshing(true);
                getArticle(false);
            }
        }, Constants.INIT_CONTENT_DELAYED);
    }

    RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            setRefreshEnable(mLayoutManager.findFirstCompletelyVisibleItemPosition() == 0);
            if (!isLoading && mAdapter != null && mLayoutManager.findLastVisibleItemPosition() == mAdapter.getItemCount() - 1) {
                isLoading = true;
                loadMore();
            }
        }
    };

    ArticleAdapter.OnItemClickListener onItemClickListener = new ArticleAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {
            Article articleInfo = mArticleList.get(position);
            Intent intent = new Intent(MainActivity.this, ArticleContentActivity.class);
            intent.putExtra("articleId", articleInfo.getId());
            startActivityForResult(intent, Constants.MAINACTIVITY_REQUEST_CODE);
        }
    };

    SwipeRefreshLayout.OnRefreshListener onRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            page = 0;
            offset = 0;
            Subscriber subscriber = new Subscriber<List<Article>>() {
                @Override
                public void onCompleted() {
                    mRefreshLayout.setRefreshing(false);
                }

                @Override
                public void onError(Throwable e) {
                    // get data from db
                    List<Article> list = Helper.getInstance().getArticleDao().queryAll(offset, LIMIT, "ctime", false);
                    if (list != null && list.size() > 0) {
                        offset = offset + list.size();
                        mArticleList.addAll(list);
                        mAdapter.notifyDataSetChanged();
                    }
                    mRefreshLayout.setRefreshing(false);
                }

                @Override
                public void onNext(List<Article> data) {
                    mArticleList.clear();
                    Helper.getInstance().getArticleDao().insertOrUpdate(data);
                    showArticleList();
                    mRefreshLayout.setRefreshing(false);
                }
            };

            DataRequest.getInstance().getArticle(subscriber, 2, page, LIMIT);
        }
    };

    private void setRefreshEnable(boolean isRefreshEnable) {
        mRefreshLayout.setEnabled(isRefreshEnable);
    }

    // 加载更多
    private void loadMore() {
        page = mArticleList.size() / LIMIT;// 计算得出当前的请求页
        getArticle(false);
    }

    private void getArticle(final boolean isRefresh) {
        Subscriber subscriber = new Subscriber<List<Article>>() {
            @Override
            public void onCompleted() {
                mRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onError(Throwable e) {
                if (page == 0) {
                    List<Article> list = Helper.getInstance().getArticleDao().queryAll(offset, LIMIT, "ctime", false);
                    if (list != null && list.size() > 0) {
                        offset = offset + list.size();
                        mArticleList.addAll(list);
                        mAdapter.notifyDataSetChanged();
                    } else {
                        LoadStateUtil.stateChange(mRefreshLayout, loadFail, StateEnum.LOAD_FAIL);
                    }
                }
                mRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onNext(List<Article> data) {
                Helper.getInstance().getArticleDao().insertOrUpdate(data);// save to db
                if (isRefresh) {
                    mArticleList.clear();
                }
                showArticleList();
            }
        };

        DataRequest.getInstance().getArticle(subscriber, 2, page, LIMIT);
    }

    private void showArticleList() {
        List<Article> list = Helper.getInstance().getArticleDao().queryAll(offset, LIMIT, "ctime", false);
        if (list != null) {
            offset = offset + list.size();
            mArticleList.addAll(list);
            LoadStateUtil.stateChange(mRefreshLayout, loadFail, StateEnum.LOAD_SUCCESS);
        }
        mAdapter.notifyDataSetChanged();
        isLoading = false;
        mRefreshLayout.setRefreshing(false);
    }

    @OnClick(R.id.txtReferesh)
    void refresh() {
        page = 0;
        offset = 0;
        getArticle(true);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.MAINACTIVITY_REQUEST_CODE && resultCode == Constants.ACTICLEACTIVITY_RESULT_CODE && data != null) {
            int articleId = data.getIntExtra("article_id", -1);
            CacheUtil.getInstance(this).put(String.valueOf(articleId), true);
            mAdapter.notifyDataSetChanged();
        }
    }

}